/**
 * 给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， postorder 是同一棵树的后序遍历，请你构造并返回这颗二叉树。
 *https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
 *
 *
 *
 */
class BuildTreeByInorderAndPostorder {
    public int postorderIndex=0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postorderIndex=postorder.length-1;
        return buildTreeChild(postorder,inorder,0,postorder.length-1);
    }
    public TreeNode buildTreeChild(int[] postorder,int[] inorder,int be,int end){
        if(be>end){
            return null;
        }
        TreeNode root=new TreeNode(postorder[postorderIndex]);
        int inorderIndex=findIndex(inorder,be,end,postorder[postorderIndex]);
        if(inorderIndex==-1){
            return null;
        }
        postorderIndex--;
        
        
        root.right=buildTreeChild(postorder,inorder,inorderIndex+1,end);
        root.left=buildTreeChild(postorder,inorder,be,inorderIndex-1);
        return root;
    }
    public int findIndex(int[] inorder,int be,int end,int val){
        for(int i=be;i<=end;i++){
            if(inorder[i]==val){
                return i;
            }
        }
        return -1;
    }
}